package br.cnpq.webflowah.controle;

import java.io.File;
import java.net.URI;
import java.util.Iterator;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.ListModel;
import javax.swing.tree.TreeModel;

import org.apache.log4j.Logger;
import org.mindswap.owls.OWLSFactory;
import org.mindswap.owls.process.Process;
import org.mindswap.owls.process.execution.ProcessExecutionEngine;
import org.mindswap.query.ValueMap;

import br.cnpq.webflowah.beans.Conceito;
import br.cnpq.webflowah.beans.Operacao;
import br.cnpq.webflowah.beans.PlanoExecucao;
import br.cnpq.webflowah.beans.WorkflowSemantico;
import br.cnpq.webflowah.ontologia.ConceitoOWL;
import br.cnpq.webflowah.ontologia.WorkflowOWLS;

public class GestorWorkflow {
	private static final Logger log = Logger.getLogger(GestorWorkflow.class);

	public GestorWorkflow() {
	}

	public WorkflowSemantico doAbrirWorkflow(File f) {
		return WorkflowOWLS.recuperar(f);
	}

	public void doSalvarWorkflow(WorkflowSemantico workflow) {
		WorkflowOWLS.salvar(workflow);
	}

	public PlanoExecucao doCriarPlano(TreeModel model, List<Operacao> list)
			throws Exception {
		PlanoExecucao plano = new PlanoExecucao();
		plano.setOperacoes(list);
		plano.criar(model);
		return plano;

		// PlanoExecucao plano = new PlanoExecucao();
		// OWLKnowledgeBase kb = Repositorio.getInstance();

		// for (int i=0; list != null && i < list.size(); i++) {
		// Operacao operacao = (Operacao) list.get(i);
		// String str = operacao.getURI().toString();
		// OWLOntology ont = kb.read(str.substring(0, str.lastIndexOf("#")));
		// Process process = ont.getProcess(operacao.getURI());
		// plano.addOperacao(process, operacao);
		// kb.unload(ont);
		// }
		//
		// plano.complete();

		// return plano;
	}

	public void doCarregar(ListModel model, URI uri) throws Exception {
		// OWLKnowledgeBase kb = Repositorio.getInstance();
		// String str = uri.toString();
		// OWLOntology ont = kb.read(str.substring(0, str.lastIndexOf("#")));
		// OWLClass classe = ont.getClass(uri);
		// Iterator iter = classe.getInstances().iterator();
		// while (iter.hasNext())
		// ((DefaultListModel) model).addElement(iter.next());

		Iterator<Conceito> iterator = ConceitoOWL.recuperarInstancias(
				uri.toString()).iterator();
		StringBuffer buffer = new StringBuffer();
		Conceito conceito = null;
		while (iterator.hasNext()) {
			conceito = iterator.next();
			((DefaultListModel) model).addElement(conceito);
			buffer.append("\n\t Instancia: " + conceito);
		}
		log.debug("Carregar instancias do conceito " + uri.toString() + buffer);
		// kb.unload(ont);
	}

}
